package com.xinyi.smart_translator.audioservice

import android.Manifest
import android.R
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import androidx.annotation.RequiresPermission
import androidx.core.app.NotificationCompat
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.atomic.AtomicBoolean

class AudioStreamService2_bak1 : Service(), EventChannel.StreamHandler, MethodChannel.MethodCallHandler {
    // 音频录制相关
    private var audioRecord: AudioRecord? = null
    private val isRecording = AtomicBoolean(false)
    private val sampleRate = 44100
    private val channelConfig = AudioFormat.CHANNEL_IN_MONO
    private val audioFormat = AudioFormat.ENCODING_PCM_16BIT
    private val bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat)

    // Flutter 通信
    private lateinit var flutterEngine: FlutterEngine
    private lateinit var eventChannel: EventChannel
    private lateinit var methodChannel: MethodChannel
    private var eventSink: EventChannel.EventSink? = null

    // 通知相关
    private val notificationId = 1
    private val channelId = "audio_stream_service"

    override fun onCreate() {
        super.onCreate()

        // 1. 构造 FlutterEngine
        flutterEngine = FlutterEngine(this)

        /*// 2. 执行 Dart 代码（必须设置入口点）
        flutterEngine.dartExecutor.executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        )*/
        flutterEngine.dartExecutor.executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        )

        FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine)


        // 设置EventChannel（发送音频数据）
        eventChannel = EventChannel(flutterEngine.dartExecutor.binaryMessenger, "com.smarttranslator.audio_stream_channel")
        eventChannel.setStreamHandler(this)

        // 设置MethodChannel（接收控制指令）
        methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.smarttranslator.audio_control_channel")
        methodChannel.setMethodCallHandler(this)

        // 创建通知渠道并启动为前台服务
        createNotificationChannel()
        startForegroundService()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "音频流服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "用于后台录音服务的通知渠道"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun startForegroundService() {
        val notification = buildNotification(false)
        startForeground(notificationId, notification)
    }

    private fun updateNotification(isRecording: Boolean) {
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.notify(notificationId, buildNotification(isRecording))
    }

    private fun buildNotification(isRecording: Boolean): Notification {
        // 创建点击通知后返回的Intent（替换为你的主Activity）
        val notificationIntent = Intent(this, Class.forName("com.xinyi.smart_translator.MainActivity"))
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            notificationIntent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )

        return NotificationCompat.Builder(this, channelId)
            .setContentTitle("音频流服务")
            .setContentText(if (isRecording) "录音中..." else "等待录音")
            .setSmallIcon(if (isRecording) R.drawable.ic_media_play else R.drawable.ic_media_pause)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
    }


    @RequiresPermission(Manifest.permission.RECORD_AUDIO)
    private fun startRecording() {
        audioRecord = AudioRecord(
            MediaRecorder.AudioSource.MIC,
            sampleRate,
            channelConfig,
            audioFormat,
            bufferSize
        )

        Thread {
            try {
                audioRecord?.startRecording()
                val buffer = ByteArray(bufferSize)

                while (isRecording.get()) {
                    val bytesRead = audioRecord?.read(buffer, 0, bufferSize) ?: -1
                    if (bytesRead > 0) {

                        Handler(Looper.getMainLooper()).post {
                            eventSink?.success(buffer.copyOf(bytesRead))
                        }
                        // 发送音频数据到Flutter（注意：这里发送的是原始PCM数据）
                        // eventSink?.success(buffer.copyOf(bytesRead))
                    }
                }
            } catch (e: Exception) {
                eventSink?.error("RECORDING_ERROR", "录音过程中出错", e.message)
            } finally {
                try {
                    audioRecord?.stop()
                } catch (e: IllegalStateException) {
                    // 忽略已停止的状态错误
                }
                audioRecord?.release()
                audioRecord = null
            }
        }.start()
    }

    private fun stopRecording() {
        isRecording.set(false)
    }

    override fun onDestroy() {
        // 停止录音
        stopRecording()

        // 清理Flutter引擎
        flutterEngine.destroy()

        // 移除通知
        stopForeground(true)

        super.onDestroy()
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onListen(
        arguments: Any?,
        events: EventChannel.EventSink?
    ) {
        eventSink = events
    }

    override fun onCancel(arguments: Any?) {
        eventSink = null
    }


    @RequiresPermission(Manifest.permission.RECORD_AUDIO)
    override fun onMethodCall(
        call: MethodCall,
        result: MethodChannel.Result
    ) {

        print("call.method -----------> ${call.method}");
        when (call.method) {
            "startRecording" -> {
                if (isRecording.compareAndSet(false, true)) {
                    startRecording()
                    updateNotification(true)
                }
                result.success(null)
            }
            "stopRecording" -> {
                if (isRecording.compareAndSet(true, false)) {
                    stopRecording()
                    updateNotification(false)
                }
                result.success(null)
            }
            "isRecording" -> {
                result.success(isRecording.get())
            }
            else -> {
                print("call.method -----------> ${call.method}");
                // println('call.method')
            }
        }
    }


}